<template>
  <BasicDrawer v-bind="$attrs" destroyOnClose showFooter
              :title="getTitle" :width="adaptiveWidth" :maskClosable="true"
              @register="registerDrawer"
              @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :model="modelRef"/>
    <!--底部操作部分
    <template #insertFooter>
      <view style="float: left; margin-top: 13px; width: 60px; height: 28px; line-height: 28px">系统切换:</view>
      <JSelectInput
        v-model:value="relTenantValue"
        :options="relTenantOptions"
        :allowClear="false"
        :stringToNumber="true"
        @select="(value) => handleRelTenantChange(value)"
        style="float: left; margin-top: 13px; min-width: 220px; text-align: left"
      >
      </JSelectInput>
    </template>-->
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { defineComponent, ref, computed, unref, useAttrs, watchEffect, watch, reactive } from "vue";
import { BasicForm, useForm } from "/@/components/Form/index";
import { formSchema } from "./user.data";
import { BasicDrawer, useDrawerInner } from "/@/components/Drawer";
import {
  getUser,
  saveOrUpdateUser,
  getUserRoles,
  getUserDepartList,
  getDepartSalesList,
  getAllTenantList
} from "./user.api";
import { useDrawerAdaptiveWidth } from "/@/hooks/jeecg/useAdaptiveWidth";
import { useUserStore } from '/@/store/modules/user';
import { treeGrid } from '/@/views/system/role/role.api';

import JSelectInput from '/@/components/Form/src/jeecg/components/JSelectInput.vue';

// 声明Emits
const emit = defineEmits(["success", "register"]);
const attrs = useAttrs();
const isChange = ref(true);
const isUpdate = ref(true);
const rowId = ref("");
const departOptions = ref([]);
const salesOptions = ref([]);
// TODO [VUEN-527] https://www.teambition.com/task/6239beb894b358003fe93626
const showFooter = ref(true);

//用户缓存
const userStore = useUserStore();
//左下角可以选择数据
const relTenantOptions = ref([]);
//当前选中值
const relTenantValue   = ref('');
//表单所有值，外部可更新
const modelRef  = ref<any>({});

//获取标题
//const { adaptiveWidth } = useDrawerAdaptiveWidth();
const getTitle = computed(() => (!unref(isUpdate) ? "新增用户" : "编辑用户"));
const adaptiveWidth = 700;

//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  labelWidth: 90,
  schemas: formSchema,
  showActionButtonGroup: false
});

//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //清空表间
  await resetFields();
  showFooter.value = data?.showFooter ?? true;
  setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
  //1、清理初始化表单数据
  isUpdate.value = !!data?.isUpdate;
  modelRef.value = {};
  relTenantValue.value = ''
  relTenantOptions.value = []

  //2、当前操作是编辑
  if (unref(isUpdate)) {
    //2022-05-30 覃东梁 修改
    const user = await getUser({id: data.record.id})
    if (!user) {
      alert("用户信息查询错误，无法编辑！");
      return
    }
    //赋值表单Ref
    modelRef.value = user;
    data.record = user
    //console.info("data@@@@", data.record)
    rowId.value = data.record.id;

    //租户信息定义成数组
    if (data.record.relTenantIds && !Array.isArray(data.record.relTenantIds)) {
      data.record.relTenantIds = data.record.relTenantIds.split(",");
    } else {
      data.record.relTenantIds = [];
    }

    //console.info("relTenantValue.value", userStore.getTenant, relTenantValue.value)
    //查角色/赋值/try catch 处理，不然编辑有问题
    try {
      const userRoles = await getUserRoles({ userid: data.record.id });
      if (userRoles && userRoles.length > 0) {
        data.record.selectedroles = userRoles;
      }
    } catch (error) {
    }

    //查所属部门/赋值
    const userDepart = await getUserDepartList({ userId: data.record.id });
    if (userDepart && userDepart.length > 0) {
      data.record.selecteddeparts = userDepart.map((item) => item.value);
    //   let selectDepartKeys = Array.from(userDepart, ({ key }) => key);
    //   data.record.selecteddeparts = selectDepartKeys.join(",");
    //   departOptions.value = userDepart.map(item => {
    //     return { label: item.title, value: item.key };
    //   });
    }
    //负责部门/赋值
    data.record.departIds && !Array.isArray(data.record.departIds) && (data.record.departIds = data.record.departIds.split(","));
    //update-begin---author:zyf   Date:20211210  for：避免空值显示异常------------
    data.record.departIds = data.record.departIds == "" ? [] : data.record.departIds;
    //update-begin---author:zyf   Date:20211210  for：避免空值显示异常------------

    //收客人 2023-11-09 qindl-----------------------------
    const departSales = await getDepartSalesList({ userId: data.record.id });
    if (departSales && departSales.length > 0) {
      data.record.selectedsales = departSales.map((item) => item.value);
      // let selectDepartKeys = Array.from(departSales, ({ key }) => key);
      // data.record.selectedsales = selectDepartKeys.join(",");
      // salesOptions.value = departSales.map(item => {
      //   return { label: item.title, value: item.key };
      // });
    }
    //负责部门/赋值
    data.record.salesIds && !Array.isArray(data.record.salesIds) && (data.record.salesIds = data.record.salesIds.split(","));
    data.record.salesIds = data.record.salesIds == "" ? [] : data.record.salesIds;

    //用户权限 --- qindl 2023-05-11
    // let ddlxs = findTenantIdByddlxArray(user.ddlx, relTenantValue.value)
    // let ddfss = [];
    // if (relTenantValue.value == "1") {
    //   // 只要“&&”前面是false，结果都将返“&&”前面的值;
    //   // 只要“&&”前面是true， 结果都将返“&&”后面的值;
    //   ddfss = user.ddfs && user.ddfs.split(",").filter(item => item)
    // }

    // modelRef.value = {
    //   ddlxTenantIds: ddlxs,
    //   ddfsTenantIds: ddfss,
    //   ddlx: user.ddlx,
    //   ddfs: user.ddfs,
    //   tenantId: relTenantValue.value
    // };
  }

  //处理角色用户列表情况(和角色列表有关系)
  data.selectedroles && await setFieldsValue({ selectedroles: data.selectedroles });
  //编辑时隐藏密码/角色列表隐藏角色信息/我的部门时隐藏所属部门
  const treeData = await treeGrid();

  updateSchema([
    {
      field: "password",
      show: !unref(isUpdate)
    },
    {
      field: "confirmPassword",
      ifShow: !unref(isUpdate)
    },
    {
      field: "selectedroles",
      show: !data.isRole,
      componentProps: { treeData },
    },
    {
      field: "departIds",
      componentProps: { options: departOptions }
    },
    {
      field: "salesIds",
      componentProps: { options: salesOptions }
    },
    {
      field: "selecteddeparts",
      show: !data?.departDisabled ?? false
    },
    {
      field: "relTenantIds",
      componentProps: {
        onChange: (values, options) => {
          //console.info(values, options);
          setTenantSelect(values)
        }
      },
    },
    {
      field: "ddlxTenantIds",
      componentProps: {
        //dictCode: "ddlxType",
        mode: "multiple",
        maxTagCount: 5,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: "ddfsTenantIds",
      componentProps: {
        //dictCode: "ddlxType",
        mode: "multiple",
        maxTagCount: 5,
        disabled: relTenantValue.value == "1" ? false : true,
        getPopupContainer: () => document.body,
      },
    },
  ]);

  if (unref(isUpdate)) {
    //增加底部的系统直接切换功能，方便修改用户的多系统权限
    setTenantSelect(data.record.relTenantIds)
  }

  // 无论新增还是编辑，都可以设置表单值
  if (typeof data.record === "object") {
    setFieldsValue({
      ...data.record
    });
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !showFooter });
});

//提交事件
async function handleSubmit() {
  try {
    let values = await validate();
    setDrawerProps({ confirmLoading: true });
    values.userIdentity === 1 && (values.departIds = "");
    //提交表单
    await saveOrUpdateUser(values, unref(isUpdate));
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit("success", { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

function handleRelTenantChange(value) {
  updateSchema([
    {
      field: "ddlxTenantIds",
      component: "JDictSelectTag",
      componentProps: {
        dictCode: "policyType?tenantId=" + value,
      },
    },
    {
      field: "ddfsTenantIds",
      component: "JDictSelectTag",
      componentProps: {
        dictCode: "sys_depart,depart_name,id,1=1 order by depart_order",
      },
    },
  ])

  let user  = unref(modelRef.value)
  let ddlxs = findTenantIdByddlxArray(user.ddlx, relTenantValue.value)
  let ddfss = [];
  if (relTenantValue.value == "1") {
    // 只要“&&”前面是false，结果都将返“&&”前面的值;
    // 只要“&&”前面是true， 结果都将返“&&”后面的值;
    ddfss = user.ddfs && user.ddfs.split(",").filter(item => item)
    updateSchema([{ field: "ddfsTenantIds", componentProps: { disabled: false } }])
  } else {
    updateSchema([{ field: "ddfsTenantIds", componentProps: { disabled: true } }])
  }

  modelRef.value = {
    ddlxTenantIds: ddlxs,
    ddfsTenantIds: ddfss,
    ddlx: user.ddlx,
    ddfs: user.ddfs,
    tenantId: relTenantValue.value
  };
}

/**
 * 获取系统编号下的，ddlx值
 * @param ddlx 1#,1,2,3,|2#,1,2,3
 * @param id 左下角选择的选项值
 * @return ['1','2','3']
 */
function findTenantIdByddlxArray(ddlx, id) {
  let result: any[] = [];
  //检验参数合法
  if (!ddlx) {
    return result
  }
  //定义临时数据
  let ddlxArray: any[] = []
  //折字符串 “｜” 后，再折解 “#”
  let shuArray = ddlx.split("|")
  for (var i = 0; i < shuArray.length; i++) {
    let jinArray = shuArray[i].split("#")
    if (jinArray.length == 0) {
      continue
    }
    //将ddlx字段串，做成json对象
    ddlxArray.push({
      "tenantId" : jinArray[0],
      "ddlxs" : jinArray[1].split(",").filter(item => item),
    })
  }
  //{tenantId: '2', ddlxs: Array(6)}
  ddlxArray.forEach(item => {
    if (item.tenantId == id) {
      result = item.ddlxs;
    }
  });

  //console.info("ddlxArray@@@@", ddlxArray, result)
  return result;
}

/**
 * 底部操作 2023-05-09 qindl
 * 默认值
 * 1、查看用户分配的租户 userTenants，从数据库中获取；
 * 2、登录人选择的租户tenantId；
 * 3、遍历 userTenants 数组，找出与当前登录者一致租户Id，并赋值给 relTenantValue.value
 * 4、若 relTenantValue.value 为空，没取用户信息里的第一选项
 * 5、注意 relTenantValue.value = '' 先空这个值，再赋值；不然后面打开的数据，这个值会不变；
 */
async function setTenantSelect(relTenantIds) {
  try {
    if (relTenantIds.length > 0) {
      //获取当前用户分配的，所有租户信息
      const userTenants = await getAllTenantList({ ids: relTenantIds.join(",") });
      //格式化数据
      relTenantOptions.value = (userTenants || []).map(item => {
        if (userStore.getTenant == item.id) {
          relTenantValue.value = String(userStore.getTenant)
        }
        //console.info("relTenantOptions.value", userStore.getTenant, item.id, relTenantValue.value)
        return { value: item.id+"", label: item.name };
      });
      //还是默认，就去数据里取第一项
      relTenantValue.value = relTenantValue.value || relTenantIds[0];
      handleRelTenantChange(relTenantValue.value)
    } else {
      relTenantValue.value = ''
      relTenantOptions.value = []
    }
  } catch (error) {

  }
}
</script>
